package com.ssm.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ZkLockTest02 {

    static String work_id = Long.toHexString(System.currentTimeMillis()).toUpperCase(Locale.ROOT);
    static CuratorFramework curatorFramework;

    static {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(300, 3);
        curatorFramework = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60000, 1000, retryPolicy);
        curatorFramework.start();
    }

    public static void main(String[] args) {

        InterProcessMutex zkLock = new InterProcessMutex(curatorFramework, "/com_ssm_lock/order_check");


        while (true) {

            try {
                boolean acquire = zkLock.acquire(6, TimeUnit.SECONDS);
                if (acquire) {
                    //模拟业务执行
                    Thread.sleep(1000);
                    log.info("work_id:" + work_id + " running !");
                } else {
                    log.info("work_id:" + work_id + " get lock fail !");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
}
